package com.ruoyi.basicsystem.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.ruoyi.basicsystem.domain.AccountVo4InOutList;
import com.ruoyi.basicsystem.domain.AccountVo4List;
import com.ruoyi.bill.domain.InDetailExport;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basicsystem.domain.ZnAccount;
import com.ruoyi.basicsystem.service.IZnAccountService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 结算账号Controller
 * 
 * @author nexiaozi
 * @date 2022-02-21
 */
@RestController
@RequestMapping("/basicsystem/account")
public class ZnAccountController extends BaseController
{
    @Autowired
    private IZnAccountService znAccountService;

    /**
     * 查询结算账号列表
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZnAccount znAccount)
    {
        startPage();
        List<ZnAccount> list = znAccountService.selectZnAccountList(znAccount);
        return getDataTable(list);
    }
    /**
     * 账户统计
     */
    @PreAuthorize("@ss.hasAnyPermi('report:account:list')")
    @GetMapping("/reportaccountlist")
    public TableDataInfo reportaccountlist(ZnAccount znAccount) throws Exception {
        startPage();
        List<AccountVo4List> list = znAccountService.selectZnAccountVo4List(znAccount);

        return getDataTable(list);
    }
    /**
     * 导出账户统计列表
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:list')")
    @Log(title = "结算账号", businessType = BusinessType.EXPORT)
    @PostMapping("/reportExport")
    public void reportExport(HttpServletResponse response, ZnAccount znAccount)
    {
        startPage();
        List<AccountVo4List> list = znAccountService.selectZnAccountVo4List(znAccount);
        ExcelUtil<AccountVo4List> util = new ExcelUtil<AccountVo4List>(AccountVo4List.class);
        util.exportExcel(response, list, "账户统计");
    }
    /**
     * 导出结算账号列表
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:export')")
    @Log(title = "结算账号", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZnAccount znAccount)
    {
        List<ZnAccount> list = znAccountService.selectZnAccountList(znAccount);
        ExcelUtil<ZnAccount> util = new ExcelUtil<ZnAccount>(ZnAccount.class);
        util.exportExcel(response, list, "结算账号数据");
    }

    /**
     * 获取结算账号详细信息
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:query')")
    @GetMapping(value = "/getDetailByNumber/{billNo}")
    public AjaxResult getDetailByNumber(@PathVariable("billNo") String billNo)
    {
        return AjaxResult.success(znAccountService.selectZnAccountDetailByBillNo(billNo));
    }
    /**
     * 获取结算账号详细信息
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(znAccountService.selectZnAccountById(id));
    }
    /**
     * 结算账户的统计
     * @param
     * @return
     */

    @GetMapping(value = "/getAccountStatistics")
    public AjaxResult getAccountStatistics(ZnAccount znAccount)
    {
        AjaxResult res = new AjaxResult();
            Map<String, Object> map = znAccountService.getStatistics(znAccount);
        return AjaxResult.success(map);
    }



    /**
     * 新增结算账号
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:add')")
    @Log(title = "结算账号", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZnAccount znAccount)
    {
        return toAjax(znAccountService.insertZnAccount(znAccount));
    }

    /**
     * 修改结算账号
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:edit')")
    @Log(title = "结算账号", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZnAccount znAccount)
    {
        return toAjax(znAccountService.updateZnAccount(znAccount));
    }

    /**
     * 删除结算账号
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:remove')")
    @Log(title = "结算账号", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(znAccountService.deleteZnAccountByIds(ids));
    }

    /**
     * 查询结算账号下拉框列表
     */
//    @PreAuthorize("@ss.hasPermi('basicsystem:account:list')")
    @GetMapping("/selectlist")
    public AjaxResult selectlist(ZnAccount znAccount)
    {
        znAccount.setTenantId(SecurityUtils.getTenantId());
        znAccount.setDeleteFlag("0");
        List<ZnAccount> list = znAccountService.selectZnAccountList(znAccount);
        return AjaxResult.success(list);
    }
    /**
     * 修改结算账号
     */
    @PreAuthorize("@ss.hasPermi('basicsystem:account:default')")
    @Log(title = "结算账号", businessType = BusinessType.UPDATE)
    @GetMapping("/setDefault/{id}")
    public AjaxResult setDefault(@PathVariable("id")Long id)
    {
        return toAjax(znAccountService.setDefault(id));
    }
    /**
     * 账户流水信息
     * @param accountId
     * @param initialAmount
     * @param request
     * @return
     */
    @GetMapping(value = "/findAccountInOutList")
    public AjaxResult findAccountInOutList(
                                                 @RequestParam("accountId") Long accountId,
                                                 @RequestParam("initialAmount") BigDecimal initialAmount,
                                                 HttpServletRequest request) throws Exception{
        System.out.println(JSON.toJSONString(request.getParameterMap()));
        Map<String,String[]> paramMap = request.getParameterMap();
        String billNo =null;
        String operTimeBegin = null;
        String operTimeEnd = null;
        String type = null;
        if (paramMap.containsKey("billNo")){
            billNo =paramMap.get("billNo")[0];
        }
        if (paramMap.containsKey("operTimeBegin")){
            operTimeBegin =paramMap.get("operTimeBegin")[0];
        }
        if (paramMap.containsKey("operTimeEnd")){
            operTimeEnd =paramMap.get("operTimeEnd")[0].replace("00:00:00","23:59:59");
        }
        if (paramMap.containsKey("type")){
            type =paramMap.get("type")[0];
        }
        Map<String,Object> param = new HashMap<>();
        param.put("billNo",billNo);
        param.put("operTimeBegin",operTimeBegin);
        param.put("operTimeEnd",operTimeEnd);
        param.put("type",type);
        AjaxResult res = new AjaxResult();
        startPage();
        Map<String, Object> map = new HashMap<String, Object>();
            List<AccountVo4InOutList> dataList = znAccountService.findAccountInOutList(accountId,param);
            Long total=new PageInfo(dataList).getTotal();
        res.put("total", total);
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (AccountVo4InOutList aEx : dataList) {
                    String timeStr = aEx.getOperTime().toString();
                    BigDecimal balance = znAccountService.getAccountSum(accountId, timeStr, "date").add(znAccountService.getAccountSumByHead(accountId, timeStr, "date"))
                            .add(znAccountService.getAccountSumByDetail(accountId, timeStr, "date")).add(znAccountService.getManyAccountSum(accountId, timeStr, "date")).add(initialAmount);
                    aEx.setBalance(balance);
                    aEx.setAccountId(accountId);
                    dataArray.add(aEx);
                }
            }
        res.put("data", dataArray);

        return res;
    }
    /**
     * 账户流水信息导出
     * @param request
     * @return
     */
    @PostMapping(value = "/exportAccountInOutList")
    public void exportAccountInOutList(HttpServletResponse response, HttpServletRequest request) throws Exception{
        Map<String,String[]> paramMap = request.getParameterMap();
        String billNo =null;
        String operTimeBegin = null;
        String operTimeEnd = null;
        String type = null;
        Long accountId = null;
        BigDecimal initialAmount = BigDecimal.ZERO;
        if (paramMap.containsKey("accountId")){
            accountId =Long.parseLong(paramMap.get("accountId")[0]);
        }else{
           throw new ServiceException("账户id参数为空");
        }
        if (paramMap.containsKey("initialAmount")){
            initialAmount =new BigDecimal(paramMap.get("initialAmount")[0]);
        }else{
            throw new ServiceException("账户余额参数为空");
        }
        if (paramMap.containsKey("billNo")){
            billNo =paramMap.get("billNo")[0];
        }
        if (paramMap.containsKey("operTimeBegin")){
            operTimeBegin =paramMap.get("operTimeBegin")[0];
        }
        if (paramMap.containsKey("operTimeEnd")){
            operTimeEnd =paramMap.get("operTimeEnd")[0].replace("00:00:00","23:59:59");
        }
        if (paramMap.containsKey("type")){
            type =paramMap.get("type")[0];
        }
        Map<String,Object> param = new HashMap<>();
        param.put("billNo",billNo);
        param.put("operTimeBegin",operTimeBegin);
        param.put("operTimeEnd",operTimeEnd);
        param.put("type",type);
        startPage();
        Map<String, Object> map = new HashMap<String, Object>();
        List<AccountVo4InOutList> dataList = znAccountService.findAccountInOutList(accountId,param);
        if (null != dataList) {
            for (AccountVo4InOutList aEx : dataList) {
                String timeStr = aEx.getOperTime().toString();
                BigDecimal balance = znAccountService.getAccountSum(accountId, timeStr, "date").add(znAccountService.getAccountSumByHead(accountId, timeStr, "date"))
                        .add(znAccountService.getAccountSumByDetail(accountId, timeStr, "date")).add(znAccountService.getManyAccountSum(accountId, timeStr, "date")).add(initialAmount);
                aEx.setBalance(balance);
                aEx.setAccountId(accountId);
            }
        }
        ExcelUtil<AccountVo4InOutList> util = new ExcelUtil<AccountVo4InOutList>(AccountVo4InOutList.class);
        util.exportExcel(response, dataList, "账户流水");
    }

}
